Use Cases
CodeFusion scripting is designed to address a wide variety of real-world data processing and integration needs. By leveraging flexible JavaScript logic, CodeFusion scripts can fetch, transform, and combine data from multiple sources—making it easier to build dynamic, automated solutions. This section presents practical use cases that illustrate how to implement common data handling patterns using CodeFusion.

Overview
In many cases, data scientists generate recommended products for a customer in separate columns within a single row (e.g., reco_product1, reco_product2, etc.).
For example, if four product recommendations are stored in separate columns, it can be challenging to structure them efficiently for processing.
Problem Statement
If product data is available as an array, users can easily create a product recommendation block once, and Active Content will dynamically replicate it for each product recommendation.
Solution
Create a CodeFusion script that queries the data, extracts the column values, and outputs them as an array. This approach simplifies content rendering and processing.
Implementation
Script Details
-
Function Name: convertToArray_main (Used when publishing the API).
-
Parameter: customerId (Customer identifier).
The function performs the following tasks:
-
Retrieves product recommendations for a specific customer from a Data Management Entity (DME).
-
Filters records based on customer_id.
-
Extracts four recommendation columns (reco_prod1, reco_prod2, reco_prod3, reco_prod4).
-
Returns the results in a structured format.
Script Example
// Converts columnar recommendation data into an array for flexible processing.
function convertToArray_main(customerId) {
var output = {};
// Fetch recommendation data from DME based on the customer ID
var dmeData = dme.getDme("some_reco_data")
.withQueryFilter("customer_id", "=", customerId)
.invoke();
// Return an empty array if no data is found
if (!dmeData.data || dmeData.data.length === 0) {
output.data = [];
return output;
}
// Transform column values into an array
var recommendations = [];
dmeData.data.forEach(function(record) {
recommendations.push([
record.reco_prod1,
record.reco_prod2,
record.reco_prod3,
record.reco_prod4
]);
});
output.data = recommendations;
return output;
}
Example Response
If the customerId = "12345" has the following records in DME:
customer_id |
reco_prod1 |
reco_prod2 |
reco_prod3 |
reco_prod4 |
---|---|---|---|---|
12345 |
Product A |
Product B |
Product C |
Product D |
The API response will be:
{
"data": [
["Product A", "Product B", "Product C", "Product D"]
]
}
Benefits
-
Optimized for Dynamic Content Rendering – Instead of handling individual columns, the script automates the transformation into an array format.
-
Improved Maintainability – Developers can design a single block for recommendations, and Active Content dynamically replicates it.
-
Efficient API Responses – API consumers receive structured, ready-to-use data instead of processing columnar values manually.

Overview
In recommendation systems, it is essential to provide users with a minimum number of recommendations to enhance their experience. This use case shows how to ensure at least five recommendations by cascading calls from a primary API to a secondary data source and merging the results.
Problem Statement
The primary recommendation API may return fewer results than required for a complete experience. Relying on a single source risks incomplete or empty outputs, which can disrupt downstream processes or user interfaces.
Implementation
Script Details
-
Call the primary API (such as RR API) with the user ID.
-
Check if the API response contains fewer than 5 recommendations.
-
If the result is insufficient, fetch additional recommendations from DME using the same userId.
-
Merge the API response data with DME fallback data to complete the recommendation list.
-
Return the combined recommendation result.
Script Example
// Ensures a minimum of 5 recommendations using a primary API with DME as fallback.
function fallBackToDME_main(userId) {
var output = {};
// Step 1: Fetch recommendations from the primary API
var recsApiResponse = api.get("https://api.example.com/recommendations?userId=" + encodeURIComponent(userId))
.putHeader("Accept", "application/json")
.invokeForJson();
var recsData = recsApiResponse.json && Array.isArray(recsApiResponse.json.data)
? recsApiResponse.json.data
: [];
// Step 2: Fetch additional recommendations from DME if needed
if (recsData.length < 5) {
var dmeResponse = dme.getDme("some_reco_data")
.withQueryFilter("user_id", "=", userId)
.invoke(5 - recsData.length);
var dmeData = dmeResponse.data || [];
// Step 3: Merge recommendations, ensuring de-duplication if required
if (recsData.length && dmeData.length) {
var joined = app.join(recsData, dmeData).data;
joined.forEach(function(res) {
recsData = recsData.concat(res);
});
} else if (dmeData.length) {
recsData = recsData.concat(dmeData);
}
}
// Step 4: Return exactly 5 recommendations
output.data = recsData.slice(0, 5);
return output;
}
Example Response
API Response (Insufficient Recommendations)
{
"data": [
{
"product_id": "P123",
"product_name": "Smartphone"
},
{
"product_id": "P456",
"product_name": "Laptop"
}
]
}
DME Fallback Response (Additional Recommendations)
{
"data": [
{
"product_id": "P789",
"product_name": "Tablet"
},
{
"product_id": "P101",
"product_name": "Smartwatch"
},
{
"product_id": "P112",
"product_name": "Camera"
}
]
}
Final Merged Output
{
"data": [
{
"product_id": "P123",
"product_name": "Smartphone"
},
{
"product_id": "P456",
"product_name": "Laptop"
},
{
"product_id": "P789",
"product_name": "Tablet"
},
{
"product_id": "P101",
"product_name": "Smartwatch"
},
{
"product_id": "P112",
"product_name": "Camera"
}
]
}
Benefits
-
Ensures a Minimum Number of Recommendations – Users always receive at least 5 product recommendations.
-
Improves Personalization – The system dynamically fills gaps in the API response using fallback data.
-
Optimized API Usage – Reduces dependency on a single API by supplementing missing recommendations with DME data.

Overview
Many external systems require data to be created or updated by sending a POST request with a specific payload and custom headers. CodeFusion enables you to compose and send these requests directly from your script, supporting a wide variety of integration scenarios.
Problem Statement
You need to submit structured data—such as JSON—along with custom headers (for authentication or content type) to an external API endpoint and process the response in your workflow.
Solution
Write a CodeFusion script that:
1. Prepares the API endpoint and request payload.
2. Sets any required HTTP headers.
3. Sends the POST request.
4. Handles the response and any possible errors.
Implementation
Script Details
-
Define the API endpoint (URL) and prepare the request body.
-
Set custom headers, such as Authorization, and specify the required Content-Type.
-
Send the POST request to the API with the request payload.
-
Process and return the API response in JSON format.
Script Example
// Sends a POST request with custom headers and payload.
function submitData_main(data) {
var output = {};
var apiUrl = "https://api.example.com/submit";
try {
var apiResponse = api.post(apiUrl)
.putHeader("Content-Type", "application/json")
.putHeader("Authorization", "Bearer your_api_token_here")
.setBody(JSON.stringify(data))
.invokeForJson();
output = apiResponse.json || {};
} catch (error) {
console.log("[submitData_main] API call failed:"+ error);
output = { status: "failed", message: "Unable to submit data" };
}
return output;
}
API Response
{
"status": "success",
"message": "Data submitted successfully"
}
Benefits
-
Supports Dynamic Data Processing: Enables sending custom requests with dynamic payloads.
-
Handles API Authentication: Easily integrates authorization headers for secure API calls.
-
Ensures JSON Response Handling: Uses .invokeForJson() for automatic response parsing.